package org.hepeng.workx.spring.cloud.netflix.ribbon.loadbalancer;

import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;
import org.apache.commons.lang3.StringUtils;
import org.hepeng.workx.spring.cloud.netflix.ribbon.SafeRibbonCommandContext;
import org.springframework.util.MultiValueMap;

import java.util.List;
import java.util.Objects;


/**
 * @author he peng
 */
public class ServiceInstanceIdRule extends AbstractRequestConditionalRule {

    private static final String PARAM_NAME = "instance-id";

    @Override
    public Server choose(Object key, SafeRibbonCommandContext ribbonContext , ILoadBalancer lb) {
        List<Server> servers = lb.getAllServers();
        MultiValueMap<String, String> params = ribbonContext.getParams();
        String paramInstanceId = params.getFirst(PARAM_NAME);
        for (Server server : servers) {
            String instanceId = server.getMetaInfo().getInstanceId();
            if (StringUtils.equals(paramInstanceId , instanceId)) {
                return server;
            }
        }

        return null;
    }

    @Override
    protected boolean isSupported(Object key, SafeRibbonCommandContext ribbonContext) {
        MultiValueMap<String, String> params = ribbonContext.getParams();
        return Objects.isNull(params) || ! params.containsKey(PARAM_NAME);
    }
}
